package fr.ordre66.vlcs.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import fr.ordre66.vlcs.dto.User;


@Repository("userDao")
public class UserDao implements IUserDao {

	@PersistenceContext private EntityManager entityManager;

		/* (non-Javadoc)
		 * @see fr.ordre66.vlcs.dao.IUserDao#persist(fr.ordre66.vlcs.dto.User)
		 */
		@Override
		public void persist(User transientUser) {
			System.out.println("persisting Message instance");
			try {
				entityManager.persist(transientUser);
				System.out.println("persist successful");
			} catch (RuntimeException re) {
				System.err.println("persist failed" + re);
			}
		}
		
		/* (non-Javadoc)
		 * @see fr.ordre66.vlcs.dao.IUserDao#get(java.lang.String)
		 */
		@Override
		public User get(String login){
			System.out.println("get User");
			try {
//				Query query = entityManager.createQuery("select u from User u where u.login like :login");
//				query.setParameter("login", login);
//				return (User) query.getSingleResult();
				List<User> users = this.getAll();
				for(User u : users){
					
					if(u.getLogin().equals(login))
						return u;
				}
				return null;
			} catch (RuntimeException re) {
				System.err.println("get failed" + re);
				return null;
			}			
		}
		
		 @Override
			public List<User> getAll() {
				System.out.println("getting all users");
				try {
					Query query = entityManager.createQuery("select u from User u");
					List<User> usersList = (List<User>) query.getResultList();
					System.out.println("getAll successful");
					return usersList;
				} catch (RuntimeException re) {
					System.err.println("getAll failed "+ re);
					return new ArrayList<User>();
				}
			}
	
}
